package com.study.jdbc.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ResourceBundle;

/**
* @Name: DBUtil
* @Description: jdbc数据库连接工具类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-16 下午7:14:44 
* @Version: V1.0
 */
public class DBUtil {
	
	private static String DBDRIVER = null ;
	private static String DBURL = null ;
	private static String USERNAME = null ;
	private static String PASSWORD = null ;
	
	static {
		//读取数据库连接资源配置数据
		ResourceBundle bundle = ResourceBundle.getBundle("com/study/jdbc/db") ;
		DBDRIVER = bundle.getString("DBDRIVER") ;
		DBURL = bundle.getString("DBURL") ;
		USERNAME = bundle.getString("USERNAME") ;
		PASSWORD = bundle.getString("PASSWORD") ;
		//加载数据库连接驱动程序
		try {
			Class.forName(DBDRIVER) ;
		} catch (ClassNotFoundException e) {
			System.out.println("数据库驱动程序加载失败！");
			e.printStackTrace();
		}
	}
	
	/**
	* @Name: getConnection
	* @Description: 获取数据库连接对象
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-2-16 下午7:25:06
	* @Return: Connection 数据库连接对象
	 */
	public static Connection getConnection() {
		Connection con = null ;
		try {
			con = DriverManager.getConnection(DBURL, USERNAME, PASSWORD) ;
		} catch (Exception e) {
			System.out.println("数据库连接对象获取失败!");
			e.printStackTrace() ;
		}
		return con ;
	} 
	
	/**
	* @Name: close
	* @Description: 释放数据库连接资源
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-2-16 下午7:25:26
	* @Parameters: @param con 数据库连接对象
	* @Parameters: @param s sql语句执行对象
	* @Parameters: @param rs sql语句执行结果集
	* @Return: void 无
	 */
	public static void close(Connection con, Statement s, ResultSet rs) {
		if(con != null) {
			try {
				con.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				con = null ;
			}
		}
		if(s != null) {
			try {
				s.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				s = null ;
			}
		}
		if(rs != null) {
			try {
				rs.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				rs = null ;
			}
		}
	}

	
}
